<template>
  <div class="food-selector">
    <!-- 已选择的食物 -->
    <div v-if="selectedFoods.length > 0" class="selected-foods">
      <div class="selected-foods-header">
        <span>已选择的食物 ({{ selectedFoods.length }})</span>
        <n-button size="small" quaternary @click="clearAll">
          <n-icon :size="14">
            <Close />
          </n-icon>
          清空
        </n-button>
      </div>
      <div class="selected-foods-list">
        <n-tag
          v-for="food in selectedFoods"
          :key="food.id"
          closable
          @close="removeFood(food)"
          style="margin: 4px"
        >
          {{ food.name_zh }}
        </n-tag>
      </div>
    </div>

    <!-- 食物搜索和选择 -->
    <div class="food-search">
      <n-input
        v-model:value="searchKeyword"
        placeholder="搜索食物..."
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <n-icon :size="16">
            <Search />
          </n-icon>
        </template>
      </n-input>
      
      <div class="search-filters">
        <n-select
          v-model:value="filterType"
          placeholder="类型"
          clearable
          @update:value="handleFilter"
          :options="filterTypeOptions"
          style="width: 120px"
        />

        <n-select
          v-model:value="richInNutrients"
          placeholder="富含营养素"
          multiple
          clearable
          @update:value="handleFilter"
          :options="nutrientFilterOptions"
          style="width: 180px"
        />
      </div>
    </div>

    <!-- 食物列表 -->
    <div class="food-list" v-if="filteredFoods.length > 0">
      <div
        v-for="food in filteredFoods"
        :key="food.id"
        class="food-item"
        :class="{ selected: isSelected(food as Food) }"
        @click="toggleFood(food as Food)"
      >
        <div class="food-info">
          <div class="food-name">
            <span class="chinese-name">{{ food.name_zh }}</span>
            <span class="english-name">{{ food.name_en }}</span>
          </div>
          <div class="food-nutrients">
            <n-tag v-if="food.protein_rich" type="success" size="small">蛋白质</n-tag>
            <n-tag v-if="food.omega3_rich" type="info" size="small">Omega-3</n-tag>
            <n-tag v-if="food.fiber_rich" type="warning" size="small">纤维</n-tag>
            <n-tag v-if="food.vitamin_c_rich" type="error" size="small">维C</n-tag>
          </div>
          <div class="food-basic-info">
            <span v-if="food.energy_kcal">{{ food.energy_kcal }}kcal</span>
            <span v-if="food.protein_g">蛋白{{ food.protein_g }}g</span>
            <span v-if="food.carb_g">碳水{{ food.carb_g }}g</span>
          </div>
        </div>
        <div class="food-actions">
          <n-checkbox
            :checked="isSelected(food as Food)"
            @update:checked="(checked) => handleCheckChange(food as Food, checked)"
            @click.stop
          />
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <n-empty v-else-if="!loading" description="没有找到匹配的食物">
      <template #extra>
        <n-button size="small" @click="$router.push('/settings/foods')">
          去添加食物
        </n-button>
      </template>
    </n-empty>

    <!-- 加载状态 -->
    <n-spin v-if="loading" style="width: 100%; height: 200px;" />

    <!-- 营养统计 -->
    <div v-if="selectedFoods.length > 0" class="nutrition-summary">
      <n-divider title-placement="left">营养统计 (每100g平均)</n-divider>
      <div class="nutrition-stats">
        <div class="stat-item">
          <span class="stat-label">总能量</span>
          <span class="stat-value">{{ averageNutrition.energy }} kcal</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">蛋白质</span>
          <span class="stat-value">{{ averageNutrition.protein }} g</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">脂肪</span>
          <span class="stat-value">{{ averageNutrition.fat }} g</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">碳水化合物</span>
          <span class="stat-value">{{ averageNutrition.carb }} g</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
// import { useRouter } from 'vue-router'
import { Search, Close } from '@vicons/ionicons5'
import { useFoodsStore } from '@/stores/foods'
import type { Food } from '@/types'

interface Props {
  modelValue?: Food[]
  placeholder?: string
  disabled?: boolean
}

interface Emits {
  (e: 'update:modelValue', value: Food[]): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  placeholder: '选择食物...',
  disabled: false
})

const emit = defineEmits<Emits>()
// const router = useRouter()
const foodsStore = useFoodsStore()

// 响应式数据
const searchKeyword = ref('')
const filterType = ref<string | null>(null)
const richInNutrients = ref<string[]>([])
const selectedFoods = ref<Food[]>([...props.modelValue])

// 计算属性
const loading = computed(() => foodsStore.loading)

const filterTypeOptions = [
  { label: '系统预设', value: 'system' },
  { label: '用户自定义', value: 'user' }
]

const nutrientFilterOptions = [
  { label: '蛋白质', value: 'protein' },
  { label: 'Omega-3', value: 'omega3' },
  { label: '膳食纤维', value: 'fiber' },
  { label: '维生素C', value: 'vitamin_c' },
  { label: '钙', value: 'calcium' },
  { label: '铁', value: 'iron' }
]

const filteredFoods = computed(() => {
  let result = foodsStore.foods

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(food => 
      food.name_zh?.toLowerCase().includes(keyword) ||
      food.name_en?.toLowerCase().includes(keyword)
    )
  }

  if (filterType.value === 'system') {
    result = result.filter(food => food.is_system)
  } else if (filterType.value === 'user') {
    result = result.filter(food => !food.is_system)
  }

  if (richInNutrients.value.length > 0) {
    result = result.filter(food => {
      return richInNutrients.value.some(nutrient => {
        const key = `${nutrient}_rich` as keyof Food
        return food[key] === true
      })
    })
  }

  return result
})

const averageNutrition = computed(() => {
  if (selectedFoods.value.length === 0) {
    return { energy: 0, protein: 0, fat: 0, carb: 0 }
  }

  const totals = selectedFoods.value.reduce((acc, food) => {
    acc.energy += food.energy_kcal || 0
    acc.protein += food.protein_g || 0
    acc.fat += food.fat_g || 0
    acc.carb += food.carb_g || 0
    return acc
  }, { energy: 0, protein: 0, fat: 0, carb: 0 })

  const count = selectedFoods.value.length
  return {
    energy: Math.round(totals.energy / count),
    protein: Math.round((totals.protein / count) * 10) / 10,
    fat: Math.round((totals.fat / count) * 10) / 10,
    carb: Math.round((totals.carb / count) * 10) / 10
  }
})

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  selectedFoods.value = [...newValue]
}, { deep: true })

// 监听selectedFoods变化，向父组件发送更新
watch(selectedFoods, (newValue) => {
  emit('update:modelValue', [...newValue])
}, { deep: true })

// 方法
const handleSearch = () => {
  // 搜索逻辑已在computed中处理
}

const handleFilter = () => {
  // 筛选逻辑已在computed中处理
}

const isSelected = (food: Food) => {
  return selectedFoods.value.some(f => f.id === food.id)
}

const toggleFood = (food: Food) => {
  if (props.disabled) return
  
  const index = selectedFoods.value.findIndex(f => f.id === food.id)
  if (index > -1) {
    selectedFoods.value.splice(index, 1)
  } else {
    selectedFoods.value.push(food)
  }
}

const handleCheckChange = (food: Food, checked: boolean) => {
  if (props.disabled) return
  
  if (checked) {
    if (!isSelected(food)) {
      selectedFoods.value.push(food)
    }
  } else {
    const index = selectedFoods.value.findIndex(f => f.id === food.id)
    if (index > -1) {
      selectedFoods.value.splice(index, 1)
    }
  }
}

const removeFood = (food: Food) => {
  if (props.disabled) return
  
  const index = selectedFoods.value.findIndex(f => f.id === food.id)
  if (index > -1) {
    selectedFoods.value.splice(index, 1)
  }
}

const clearAll = () => {
  if (props.disabled) return
  selectedFoods.value = []
}

// 生命周期
onMounted(async () => {
  await foodsStore.fetchFoods()
})
</script>

<style scoped>
.food-selector {
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 16px;
  background: white;
}

.selected-foods {
  margin-bottom: 16px;
}

.selected-foods-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.selected-foods-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.food-search {
  margin-bottom: 16px;
}

.search-filters {
  display: flex;
  gap: 12px;
  margin-top: 12px;
}

.food-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
}

.food-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.2s ease;
}

.food-item:last-child {
  border-bottom: none;
}

.food-item:hover {
  background: #f9f9f9;
}

.food-item.selected {
  background: #e6f7ff;
  border-color: #91d5ff;
}

.food-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.food-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chinese-name {
  font-weight: 500;
  color: #333;
}

.english-name {
  font-size: 12px;
  color: #666;
  font-style: italic;
}

.food-nutrients {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.food-basic-info {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #666;
}

.food-actions {
  margin-left: 12px;
}

.nutrition-summary {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.nutrition-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 12px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f9f9f9;
  border-radius: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.stat-value {
  font-weight: 500;
  color: #333;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .search-filters {
    flex-direction: column;
  }
  
  .nutrition-stats {
    grid-template-columns: 1fr 1fr;
  }
  
  .food-basic-info {
    flex-direction: column;
    gap: 2px;
  }
}
</style>
